# -*- coding:utf-8 -*-
import json

from django.shortcuts import render, render_to_response, redirect, reverse, HttpResponse
from django.views.generic.base import View
from django.contrib.auth.backends import ModelBackend
from django.http import JsonResponse
from captcha.models import CaptchaStore
from django.contrib.auth import authenticate, login, logout
from django.db.models import Q
from django.contrib.auth.hashers import make_password
from pure_pagination import Paginator, PageNotAnInteger

from .forms import LoginForm, RegisterForm, ForgetForm, ResetForm, ReleaseMenuForm
from .models import UserProfile, EmailVerifyRecord, Banner
from cookbook.models import Menu, MenuType
from community.models import Topic
from utils.email_send import send_register_email
from utils.mixin_utils import LoginRequireMixin
from operation.models import UserConcern, UserFavorite


class CustomBackend(ModelBackend):
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


class LoginView(View):
    def get(self, request):
        login_form = LoginForm()
        return render(request, 'login.html', {'form': login_form})

    def post(self, request):
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            data = login_form.cleaned_data
            user_name = data['username']
            pass_word = data['password']
            user = authenticate(username=user_name, password=pass_word)
            if user:
                if user.is_active:
                    login(request, user)
                    return redirect(reverse('index'))
                else:
                    return render(request, 'login.html', {'msg': '用户未激活！', 'form': login_form})
            else:
                return render(request, 'login.html', {'msg': '用户名或密码错误!', 'form': login_form})
        else:
            return render(request, 'login.html', {'form': login_form, 'msg': '验证码错误！'})


class LogoutView(View):
    def get(self, request):
        logout(request)
        return redirect(reverse('index'))


def ajax_val(request):
    if request.is_ajax():
        cs = CaptchaStore.objects.filter(response=request.GET['response'], hashkey=request.GET['hashkey'])
        if cs:
            json_data = {'status': 1}
        else:
            json_data = {'status': 0}
        return JsonResponse(json_data)
    else:
        json_data = {'status': 0}
        return JsonResponse(json_data)


class RegisterView(View):
    def get(self, request):
        register_form = RegisterForm()
        return render(request, 'register.html', {'form': register_form})

    def post(self, request):
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            email = request.POST.get('email')
            user_name = request.POST.get('username')
            if UserProfile.objects.filter(email=email):
                return render(request, 'register.html', {'form': RegisterForm(), 'msg': '邮箱已被注册！'})
            elif UserProfile.objects.filter(username=user_name):
                return render(request, 'register.html', {'form': RegisterForm(), 'msg': '用户已存在！'})
            else:
                pass_word = request.POST.get('password')
                user = UserProfile.objects.create(username=user_name, is_active=False, email=email,
                                                  password=make_password(pass_word))
                user.save()
                send_register_email(email, 'register')
                return render(request, 'send_sucess.html')
        else:
            return render(request, 'register.html', {'form': RegisterForm()})


class ActiveUserView(View):
    def get(self, request, active_code):
        all_records = EmailVerifyRecord.objects.filter(code=active_code)
        if all_records:
            for record in all_records:
                email = record.email
                user = UserProfile.objects.get(email=email)
                user.is_active = True
                user.save()
                login(request, user)
                return redirect(reverse('index'))
        else:
            return render(request, 'active-fail.html')


class ForgetView(View):
    def get(self, request):
        forget_form = ForgetForm()
        return render(request, 'forget-password.html', {'form': forget_form})

    def post(self, request):
        forget_form = ForgetForm(request.POST)
        if forget_form.is_valid():
            email = request.POST.get('email')
            if UserProfile.objects.filter(email=email):
                send_register_email(email, 'forget')
                return render(request, 'send_sucess.html')
            else:
                return render(request, 'forget-password.html', {'form': ForgetForm(), 'msg': '用户不存在！'})
        else:
            return render(request, 'forget-password.html', {'form': forget_form, 'msg': '验证码错误！'})


class ResetView(View):
    def get(self, request, active_code):
        all_records = EmailVerifyRecord.objects.filter(code=active_code)
        if all_records:
            for record in all_records:
                email = record.email
                return render(request, 'password-reset.html', {'email': email})
        else:
            return render(request, 'active-fail.html')
        return render(request, 'login.html')


class ModifypwdView(View):
    def post(self, request):
        reset_form = ResetForm(request.POST)
        if reset_form.is_valid():
            password1 = request.POST.get('password1')
            password2 = request.POST.get('password2')
            email = request.POST.get('email')
            if password1 != password2:
                return render(request, 'password-reset.html', {'email': email, 'msg': '密码不一致'})
            user = UserProfile.objects.get(email=email)
            user.password = make_password(password1)
            user.save()

            return redirect(reverse('login'))
        else:
            email = request.POST.get('email')
            return render(request, 'password-reset.html', {'email': email})


class IndexView(View):
    def get(self, request):
        banners = Banner.objects.all().order_by('index')
        hot_menu = Menu.objects.all().order_by('-click_number')[:8]
        hot_topic = Topic.objects.all().order_by('-click_number')[:6]
        return render(request, 'index.html', {
            'banners': banners,
            'hot_menu': hot_menu,
            'hot_topic': hot_topic
        })


class UserInfoView(LoginRequireMixin, View):
    def get(self, request):
        return render(request, 'user-info.html')

    def post(self, request):
        user = UserProfile.objects.get(username=request.user)
        user.username = request.POST.get('username')
        user.email = request.POST.get('email')
        user.gender = request.POST.get('gender')
        user.mobile = request.POST.get('mobile')
        user.address = request.POST.get('address')
        user.save()
        return redirect(reverse('users:user_info'))


class UserFriendView(LoginRequireMixin, View):
    def get(self, request):
        concerns = UserConcern.objects.filter(user_id=int(request.user.id))
        my_concerns = []
        for concern in concerns:
            if concern.is_concern:
                my_concerns.append(concern)
        return render(request, 'user-friend.html', {
            'user_concerns': my_concerns,
        })


class UserKitchenView(LoginRequireMixin, View):
    def get(self, request):
        release_form = ReleaseMenuForm()
        my_menus = Menu.objects.filter(user=request.user).order_by('-add_time')
        favorites = UserFavorite.objects.filter(user=request.user)
        my_favorites = []
        for favorite in favorites:
            if favorite.is_fav:
                my_favorites.append(favorite)
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        p = Paginator(my_menus, 4, request=request)
        my_menus = p.page(page)
        return render(request, 'user-kitchen.html', {
            'release_form': release_form,
            'my_menus': my_menus,
            'my_favorites': my_favorites,
        })

    def post(self, request):
        release_form = ReleaseMenuForm(request.POST)
        if release_form.is_valid():
            menu = Menu()
            menu.name = request.POST.get('name')
            menu.user = request.user
            menu.image = request.FILES.get('image')
            menu.menu_tpye_id = int(request.POST.get('menu_type'))
            menu.ingredients = request.POST.get('ingredients')
            menu.details = request.POST.get('details')
            menu.save()
            menu_type = MenuType.objects.get(id=int(request.POST.get('menu_type')))
            menu_type.number += 1
            menu_type.save()
        return redirect(reverse('users:user_kitchen'))


def change_pwd(request):
    password1 = request.POST.get('password1')
    password2 = request.POST.get('password2')
    if password1 and password2 and password1 == password2:
        user = UserProfile.objects.get(username=request.user)
        user.password = make_password(password1)
        user.save()
        login(request, user)
        return HttpResponse(json.dumps({'status': 1}), content_type='application/json')
    return HttpResponse(json.dumps({'status': 0}), content_type='application/json')


def change_image(request):
    image = request.FILES.get('file')
    if image:
        user = UserProfile.objects.get(username=request.user)
        user.image = image
        user.save()
        return HttpResponse(json.dumps({'status': 1}), content_type='application/json')
    return HttpResponse(json.dumps({'status': 0}), content_type='application/json')


def page_not_found(request):
    response = render_to_response('404.html')
    response.status_code = 404
    return response


def server_error(request):
    response = render_to_response('500.html')
    response.status_code = 500
    return response
